package com.ypf.rpc.nettyHandler;

import com.ypf.rpc.factory.RegisterFactory;
import com.ypf.rpc.loadBalancer.RoundRobinRule;
import com.ypf.rpc.manager.register.pojo.RegisterInfo;
import com.ypf.rpc.message.RpcQueryRegisterRequestMessage;
import com.ypf.rpc.message.RpcQueryRegisterResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.ArrayList;
import java.util.List;

@ChannelHandler.Sharable
public class RpcQueryRegisterRequestMessageHandler extends SimpleChannelInboundHandler<RpcQueryRegisterRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcQueryRegisterRequestMessage message) throws Exception {

        RpcQueryRegisterResponseMessage responseMessage = new RpcQueryRegisterResponseMessage();

        responseMessage.setSequenceId(message.getSequenceId());  // 设置信息id

        String serverName = message.getServerName();  // 查询的服务名称
        List<RegisterInfo> registerFactory = RegisterFactory.registerFactory;

        List<RegisterInfo> waitingServerRegister = new ArrayList<>();

        for (RegisterInfo registerInfo : registerFactory) {
            // 循环遍历注册中心所有服务 如果服务名称与请求查询的服务名称相等
            // 就放到等待服务列表中
            if (registerInfo.getServerName().equals(serverName)){
                waitingServerRegister.add(registerInfo);
            }
        }

        if (waitingServerRegister.size()==0){   // 等待服务列表为0 说明没有服务 直接返回null
            responseMessage.setServerPort(null);
            responseMessage.setServerHost(null);

        }else {
            // 创建负载均衡策略
            RoundRobinRule roundRobinRule = new RoundRobinRule();
            // 将等待服务列表交由 负载均衡策略选择
            RegisterInfo registerInfo = roundRobinRule.getRegisterInfo(waitingServerRegister);

            // 设置由负载均衡策略选中的ip地址
            responseMessage.setServerHost(registerInfo.getInetSocketAddress().getHostName());

            // 设置由负载均衡策略选中的端口号
            responseMessage.setServerPort(registerInfo.getInetSocketAddress().getPort());
        }

        ctx.writeAndFlush(responseMessage);

    }
}
